'''
Created on 2013. 5. 13.

@author: Lee
'''

from google.appengine.api import channel, images
from google.appengine.ext import ndb, blobstore
from google.appengine.ext.webapp import blobstore_handlers
from kr.community.configure import JINJA_ENVIRONMENT
from kr.community.gaesessions import get_current_session
from kr.community.models import ChatList, ChannelSession, Image
import json
import logging
import urllib
import webapp2

class GalleryPage(webapp2.RequestHandler):
    '''
        This is Main Page.
        Summary of site contents.
    '''

    def get(self):
        session = get_current_session()
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('gallery.html')
        
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user = user_key.get()
            template_values['user'] = user
            
            chat_token = channel.create_channel(session['user'])
            template_values['chat_token'] = chat_token
            template_values['chat_list'] = ChatList.query().order(-ChatList.timestamp).fetch(200)
            template_values['chat_list'].reverse()
            
            for chat_entry in template_values['chat_list']:
                start_idx = -1
                end_idx = -1
                http_flag = True
                try:
                    start_idx = chat_entry.msg.index("http")
                except ValueError:
                    try:
                        start_idx = chat_entry.msg.index("www")
                        http_flag = False   
                    except ValueError:
                        continue
                try:
                    end_idx = chat_entry.msg.index(" ", start_idx)
                except ValueError:
                    end_idx = len(chat_entry.msg)
                link = chat_entry.msg[start_idx:end_idx]
                if http_flag:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='%s' target='_blank'>%s</a>"%(link, link))
                else:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='http://%s' target='_blank'>%s</a>"%(link, link))
            template_values['user_list'] = ChannelSession.query()
            page = 1
            if self.request.GET.has_key("page"):
                page = int(self.request.GET['page'])
            template_values['cur_page'] = page
            entry_count = Image.query().count()
            page_count = entry_count/20
            if entry_count%20 != 0:
                page_count += 1
            template_values['page_list'] = range(1, page_count+1)
            template_values['gallery_list'] = Image.query().order(-Image.timestamp).fetch(page*20)[(page-1)*20:]
                
            
            self.response.write(template.render(template_values))
        else:
            self.redirect("/login/")
            
class GalleryPostPage(webapp2.RequestHandler):
    def get(self):
        session = get_current_session()
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('gallery_post.html')
        
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user = user_key.get()
            template_values['user'] = user
            
            chat_token = channel.create_channel(session['user'])
            if self.request.GET.has_key("error"):
                template_values['error'] = self.request.GET['error']
            template_values['chat_token'] = chat_token
            template_values['chat_list'] = ChatList.query().order(-ChatList.timestamp).fetch(200)
            template_values['chat_list'].reverse()
            
            for chat_entry in template_values['chat_list']:
                start_idx = -1
                end_idx = -1
                http_flag = True
                try:
                    start_idx = chat_entry.msg.index("http")
                except ValueError:
                    try:
                        start_idx = chat_entry.msg.index("www")
                        http_flag = False   
                    except ValueError:
                        continue
                try:
                    end_idx = chat_entry.msg.index(" ", start_idx)
                except ValueError:
                    end_idx = len(chat_entry.msg)
                link = chat_entry.msg[start_idx:end_idx]
                if http_flag:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='%s' target='_blank'>%s</a>"%(link, link))
                else:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='http://%s' target='_blank'>%s</a>"%(link, link))
            template_values['user_list'] = ChannelSession.query()
            template_values['action_url'] = blobstore.create_upload_url('/gallery/upload/')
            
            self.response.write(template.render(template_values))
        else:
            self.redirect("/login/")
            
    def post(self):
        session = get_current_session()
        template_values = {}
        
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user = user_key.get()
            template_values['user'] = user
            if not session.has_key('local_gallery'):
                self.redirect("/gallery/post/?error=not_image")
                return
            logging.critical(session['local_gallery'])
            for img_key in session['local_gallery']:
                img = Image()
                img.content = self.request.POST.get("content", "")
                img.uploader = user.user_nickname
                img.image_key = img_key
                img.put()

            del session['local_gallery']
            self.redirect("/gallery/")
        else:
            self.redirect("/login/")
            
class UploadImage(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        session = get_current_session()
        msg = json.dumps({"success": False, "msg":"AUTH"})
        
        if session.is_active():
            if not session.has_key("local_gallery"):
                session['local_gallery'] = []
            else:
                for img_key in session['local_gallery']:
                    resource = str(urllib.unquote(img_key))
                    try:
                        blobstore.BlobInfo.get(resource).delete()
                    except:
                        pass
                    
            upload_files = self.get_uploads('upload_img[]')
            
            for file_entry in upload_files:
                session['local_gallery'].append(str(file_entry.key()))
            logging.critical(session['local_gallery'])
            msg = json.dumps({"success": True, "msg":"Success"})    
        self.response.write(msg)
            
class ServeImage(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        session = get_current_session()
        if session.is_active():
            if "thum" in str(resource):
                resource = str(resource).replace("thum", "")
                img = images.Image(blob_key=resource)
                img.resize(width=80, height=100)
                #thumbnail = img.execute_transforms()

                self.response.headers['Content-Type'] = 'image/jpeg'
                blob_info = blobstore.BlobInfo.get(resource)
                self.send_blob(blob_info)
                #self.response.out.write(thumbnail)
            else:
                resource = str(urllib.unquote(resource))
                blob_info = blobstore.BlobInfo.get(resource)
                self.send_blob(blob_info)
        else:
            self.redirect("/login/")

class ServeContent(webapp2.RequestHandler):
    def get(self, resource):
        session = get_current_session()
        if session.is_active():
            img_list = Image.query(Image.image_key==resource)
            content = ""
            
            for img in img_list:
                start_idx = -1
                end_idx = -1
                http_flag = True
                try:
                    start_idx = img.content.index("http")
                except ValueError:
                    try:
                        start_idx = img.content.index("www")
                        http_flag = False   
                    except ValueError:
                        pass
                except AttributeError:
                    img.content = ""
                try:
                    end_idx = img.content.index(" ", start_idx)
                except ValueError:
                    end_idx = len(img.content)
                link = img.content[start_idx:end_idx]
                if http_flag:
                    img.content = img.content.replace(link, "<a href='%s' target='_blank'>%s</a>"%(link, link))
                else:
                    img.content = img.content.replace(link, "<a href='http://%s' target='_blank'>%s</a>"%(link, link))
                content = img.uploader+","+img.content
                
                
            self.response.write(content)
        else:
            self.response.write("AUTH")